# 110. 平衡二叉树
var isBalanced = function(root) {
return height(root) >= 0
}
function height(root) {
if (!root) return 0
let leftHeight, righttHeight
if (
(leftHeight = height(root.left)) === -1 ||
(righttHeight = height(root.right)) === -1 ||
Math.abs(leftHeight - righttHeight) > 1
) {
return -1
} else {
return Math.max(leftHeight, righttHeight) + 1
}
}
console.log(
isBalanced({
val: 3,
left: {
val: 9,
},
right: {
val: 20,
left: {
val: 15,
},
right: {
val: 7,
},
},
})
)
console.log(
isBalanced({
val: 1,
left: {
val: 2,
left: {
val: 3,
left: {
val: 4,
},
right: {
val: 4,
},
},
right: {
val: 3,
},
},
right: {
val: 2,
},
})
)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59